/**
 * 
 */
package com.ken.work.tools.tools.generation;

import java.io.File;
import java.io.FileWriter;
import java.util.List;
import java.util.Set;

import com.ken.work.tools.tools.Contants;
import com.ken.work.tools.tools.db.DBUtil;
import com.ken.work.tools.tools.freemarker.FreeMarkerUtil;
import com.ken.work.tools.tools.model.ColumnModel;
import com.ken.work.tools.tools.model.TableModel;
import com.ken.work.tools.tools.utils.DataTypeUtil;
import com.ken.work.tools.tools.utils.UnderlineCamel;

import cn.hutool.core.io.FileUtil;
import freemarker.template.Template;

/**
 * @desc {生成java model 的工具类}
 * @author Liuk
 * @date 2017年4月20日 下午5:31:37
 * @version v1.0-
 */
public class ModelRunning {

	/**
	 * 生成model代码
	 * @throws Exception
	 */
	public static void generation(){
		try {
			System.out.println("---------------code generation {{model}} running ----------------");
			//获取数据中的所有表
			List<String> tableList = DBUtil.getTableName();
			for (String tableName : tableList) {
				generation(tableName);
			}
			System.out.println("---------------code generation {{model}} end-----------------");
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("---------------code generation {{model}} failed-----------------");
			e.printStackTrace();
		}
		
	}
	
	public static void generation(String tableName) throws Exception{
		TableModel model = getTableData(/* Contants.Model.packagename, */ tableName);
		Template template = FreeMarkerUtil.getTemplate("model.ftl");
		System.out.println("---------------code generation {{table}} " + tableName +" {{Class}} " + model.getClassName() + " successed-----------------");
		FileWriter fileWriter = new FileWriter(FileUtil.newFile(Contants.Model.getOutPath(model.getClassName()) + File.separator + model.getClassName() + ".java"));
		template.process(model, fileWriter);
	}
	
	/**
	 * 获取生成实体类的数据
	 * @param packageName
	 * @param tableName
	 * @return
	 */
	private static TableModel getTableData(/* String packageName, */String tableName){
		TableModel model = new TableModel();
		model.setTableName(tableName);
		
		
		model.setTableDesc(DBUtil.getTableNote(tableName));
		
		//获取表中的字段
		List<ColumnModel> columnList = DBUtil.getCols(tableName);
		tableName = UnderlineCamel.underline2Camel(tableName, true,Contants.table_pre);
		tableName = UnderlineCamel.getFirstUpper(tableName);
		model.setColumnList(columnList);
		Set<String> packageSet = DataTypeUtil.getDataPackage(columnList);
		model.setPackageList(packageSet);
		model.setClassName(tableName + "");
		
		
		model.setPackageName(Contants.Model.getPackagename(tableName + ""));
		
		return model;
	}
}
